package coffeenc.mall.security.component;

import coffeenc.mall.common.jwt.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Jwt授权过滤器
 * Created by coffeenc on 2020/10/22
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

     @Value("${jwt.tokenHeaderKey}")
     private String tokenHeaderKey;
     @Autowired
     private UserDetailsService userDetailsService;
     @Autowired
     private JwtTokenUtil jwtTokenUtil;
     @Override
     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
          /**
           * 从Http Header 中获取Token字符串
           */
          String authToken = request.getHeader(this.tokenHeaderKey);
          if (authToken!=null){
               /**
                * 从Token中分离出用户名信息
                */
               String username = jwtTokenUtil.getUserNameFromToken(authToken);
               if (username!=null && SecurityContextHolder.getContext().getAuthentication()==null){
                    /**
                     * 根据用户名加载UserDetails对象
                     */
                    UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                    if (jwtTokenUtil.validateToken(authToken,userDetails)){
                         /**
                          * 由UserDetails对象初始化一个UsernamePasswordAuthenticationToken对象
                          * 实际上是将UserDetails对象中信息转存到UsernamePasswordAuthenticationToken对象中
                          */
                         UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                         /**
                          * 将用户的详情信息（此处为请求信息）存储到Authentication对象的details字段中
                          * Authentication对象的details字段存储用户的详细信息，比如用户的请求等
                          */
                         authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                         /**
                          * 将用户的授权信息（Authentication对象）存入安全上下文中
                          */
                         SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
               }
          }
          /**
           * 本过滤器已完成，执行过滤器链的下一个过滤器
           */
          filterChain.doFilter(request,response);
     }
}
